package com.baiyun.security;

import com.baiyun.domain.User;
import com.baiyun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return new AccountUser(user.getId(),user.getUsername(),user.getPassword(),getUserAuthority(user.getId()));
    }

    /**
     * 获取用户权限信息（角色，菜单）
     * @param id
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long id){
        //角色、菜单权限
        String authority = userService.getUserAuthority(id); //ROLE_ADMIN,sys:user:list,...
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
